<template>
  <div class="prescription-medicine-management">
    <!-- 顶部导航栏 -->
    <div class="bg-white shadow-sm p-4">
      <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <!-- 操作按钮和搜索 -->
      <div class="mb-6 flex justify-between items-center">
        <div>
          <el-button
            type="primary"
            size="medium"
            @click="openAddDialog()"
            :icon="Plus"
          >
            新增处方药品
          </el-button>
        </div>
        <div class="w-64">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索药品名称或处方ID"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <el-table
          :data="prescriptionMedicines"
          v-loading="loading"
          stripe
          border
          fit
          highlight-current-row
          class="min-w-full"
        >
          <el-table-column prop="id" label="记录ID" width="100" align="center" />
          <el-table-column label="药品信息" width="220">
            <template #default="{ row }">
              <div class="flex items-center">
                <div class="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center mr-2">
                  <el-icon class="text-green-600">
                    <FirstAidKit />
                  </el-icon>
                </div>
                <div>
                  <p class="text-sm font-medium">{{ row.medicine?.medicineName || '未知药品' }}</p>
                  <p class="text-xs text-gray-500">{{ row.medicine?.specifications || '无规格信息' }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="dosage" label="用法用量" width="180" />
          <el-table-column prop="quantity" label="数量" width="100" align="center" />
          <el-table-column label="处方信息" width="260">
            <template #default="{ row }">
              <div>
                <p class="text-sm font-medium">{{ row.prescription?.patient?.realName || '未知患者' }}</p>
                <p class="text-xs text-gray-500">
                  <el-icon class="text-gray-400 mr-1">
                    <User />
                  </el-icon>
                  {{ row.prescription?.doctor?.realName || '未知医生' }}
                </p>
                <p class="text-xs text-gray-500">
                  <el-icon class="text-gray-400 mr-1">
                    <Clock />
                  </el-icon>
                  {{ row.prescription?.createTime ? formatDate(row.prescription.createTime) : '未记录时间' }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="mini"
                @click="openEditDialog(row)"
                class="mr-2"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(row.id)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑处方药品' : '新增处方药品'"
        width="560px"
        :close-on-click-modal="false"
        @closed="handleDialogClosed"
      >
        <el-form
          :model="form"
          :rules="formRules"
          ref="formRef"
          label-width="120px"
          class="px-4"
        >
          <el-form-item label="记录ID" prop="id" v-if="isEditMode">
            <el-input v-model.number="form.id" disabled />
          </el-form-item>
          
          <el-form-item label="处方ID" prop="prescriptionId">
            <el-input
              v-model.number="form.prescriptionId"
              placeholder="请输入处方ID"
              clearable
              type="number"
            />
          </el-form-item>
          
          <el-form-item label="药品ID" prop="medicineId">
            <el-input
              v-model.number="form.medicineId"
              placeholder="请输入药品ID"
              clearable
              type="number"
            />
          </el-form-item>
          
          <el-form-item label="用法用量" prop="dosage">
            <el-input
              v-model.trim="form.dosage"
              placeholder="请输入用法用量"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="数量" prop="quantity">
            <el-input-number
              v-model.number="form.quantity"
              :min="1"
              :max="999"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitLoading"
            >
              {{ isEditMode ? '保存修改' : '新增记录' }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus';
import {
  FirstAidKit,
  User,
  Clock,
  Plus,
  Search,
  Edit,
  Delete
} from '@element-plus/icons-vue';
import axios from 'axios';
import Navigation from '@/components/Navigation.vue';

// 定义数据类型
interface Medicine {
  medicineId: number;
  medicineName: string;
  specifications?: string;
}

interface User {
  userId: number;
  realName: string;
}

interface Prescription {
  prescriptionId: number;
  patient: User;
  doctor: User;
  createTime: number;
}

interface PrescriptionMedicine {
  id: number;
  prescriptionId: number;
  medicineId: number;
  dosage: string;
  quantity: number;
  prescription: Prescription | null;
  medicine: Medicine | null;
}

// 状态管理
const homeRoute = '/';
const currentPage = '处方药品管理';
const prescriptionMedicines = ref<PrescriptionMedicine[]>([]);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const searchKeyword = ref('');
const formRef = ref<FormInstance>();

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表单数据
const form = reactive({
  id: 0,
  prescriptionId: 0,
  medicineId: 0,
  dosage: '',
  quantity: 1
});

// 表单验证规则
const formRules = reactive({
  prescriptionId: [
    { required: true, message: '请输入处方ID', trigger: 'blur' },
    { 
      type: 'number', 
      message: '请输入有效数字', 
      trigger: 'blur',
      transform: (value: string) => Number(value) 
    }
  ],
  medicineId: [
    { required: true, message: '请输入药品ID', trigger: 'blur' },
    { 
      type: 'number', 
      message: '请输入有效数字', 
      trigger: 'blur',
      transform: (value: string) => Number(value) 
    }
  ],
  dosage: [
    { required: true, message: '请输入用法用量', trigger: 'blur' },
    { min: 2, message: '用法用量至少2个字符', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
});

// 日期格式化函数
const formatDate = (timestamp: number) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 将下划线命名转换为驼峰命名
const underlineToCamel = (str: string) => {
  return str.replace(/_(\w)/g, (_, letter) => letter.toUpperCase());
};

// 递归转换对象属性名（从下划线到驼峰）
const transformObject = (obj: any): any => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (Array.isArray(obj)) {
    return obj.map(item => transformObject(item));
  }
  
  const newObj: any = {};
  for (const [key, value] of Object.entries(obj)) {
    const camelKey = underlineToCamel(key);
    newObj[camelKey] = transformObject(value);
  }
  
  return newObj;
};

// 将驼峰命名转换为下划线命名
const camelToUnderline = (str: string) => {
  return str.replace(/([A-Z])/g, '_$1').toLowerCase();
};

// 递归转换对象属性名（从驼峰到下划线）
const transformRequestData = (obj: any): any => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (Array.isArray(obj)) {
    return obj.map(item => transformRequestData(item));
  }
  
  const newObj: any = {};
  for (const [key, value] of Object.entries(obj)) {
    const underlineKey = camelToUnderline(key);
    newObj[underlineKey] = transformRequestData(value);
  }
  
  return newObj;
};

// 加载数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      keyword: searchKeyword.value
    };
    
    const response = await axios.get("/prescriptionmedicine/findAll", { params });
    
    // 适配后端返回的数组格式
    if (Array.isArray(response.data)) {
      prescriptionMedicines.value = response.data.map(item => transformObject(item));
      pagination.total = response.data.length;
    } else {
      throw new Error("返回数据格式不正确");
    }
  } catch (error) {
    console.error('数据加载失败:', error);
    ElMessage.error('数据加载失败: ' + (error as Error).message);
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchData();
};

// 清除搜索
const handleSearchClear = () => {
  searchKeyword.value = '';
  pagination.currentPage = 1;
  fetchData();
};

// 打开新增对话框
const openAddDialog = () => {
  resetForm();
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row: PrescriptionMedicine) => {
  resetForm(row);
  isEditMode.value = true;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = (data?: PrescriptionMedicine) => {
  form.id = data?.id || 0;
  form.prescriptionId = data?.prescriptionId || 0;
  form.medicineId = data?.medicineId || 0;
  form.dosage = data?.dosage || '';
  form.quantity = data?.quantity || 1;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    const isValid = await formRef.value.validate();
    if (!isValid) return;

    submitLoading.value = true;
    
    // 转换请求数据的属性名
    const requestData = transformRequestData({
      id: form.id,
      prescriptionId: form.prescriptionId,
      medicineId: form.medicineId,
      dosage: form.dosage.trim(),
      quantity: form.quantity
    });

    const response = isEditMode.value
      ? await axios.post("/prescriptionmedicine/update", requestData)
      : await axios.post("/prescriptionmedicine/add", requestData);

    // 适配后端返回的字符串响应
    if (response.data === '添加成功' || response.data === '修改成功') {
      ElMessage.success(isEditMode.value ? '修改成功' : '新增成功');
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response.data || '操作失败，请重试');
    }
  } catch (error: any) {
    console.error('操作失败:', error);
    if (error.response) {
      ElMessage.error(`操作失败: ${error.response.status} ${error.response.data}`);
    } else {
      ElMessage.error('网络错误，请检查连接');
    }
  } finally {
    submitLoading.value = false;
  }
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该记录吗？此操作不可撤销！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        distinguishCancelAndClose: true
      }
    );
    
    // 用户确认删除
    const response = await axios.post('/prescriptionmedicine/delete', { id });
    
    // 适配后端返回的字符串响应
    if (response.data === '删除成功') {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response.data || '删除失败，请重试');
    }
  } catch (error) {
    // 用户取消删除
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败: ' + (error as Error).message);
    }
  }
};

// 对话框关闭后重置表单
const handleDialogClosed = () => {
  formRef.value?.resetFields();
};

// 初始化数据
onMounted(fetchData);
</script>

<style scoped>
.prescription-medicine-management {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-table__header th {
  background-color: #f8fafc;
  color: #334155;
  font-weight: 500;
}

.el-table__row:hover {
  background-color: #f1f5f9 !important;
}

.el-dialog__header {
  background-color: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  padding: 16px 20px;
}

.el-dialog__title {
  font-weight: 500;
  color: #1e293b;
  font-size: 16px;
}

.el-form-item__label {
  color: #475569;
  font-weight: 500;
}

.el-input__inner:focus,
.el-select__input:focus,
.el-textarea__inner:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.el-pagination {
  padding: 12px 0;
}
</style>